package com.cqc.jdk8.Jutil.concurrent;

import org.junit.Test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceTest {

    /**
     * 无效，必须放到main方法中
     */
    @Test
    public void f1() {
        beepForAnHour();
    }

    public static void main(String[] args) {
        beepForAnHour();
    }

    /**
     * 每10s执行1次beeperHandle，60s后停止任务。
     */
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void beepForAnHour() {
        final Runnable beeper = new Runnable() {
            public void run() {
                System.out.println("beep");
            }
        };
        final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, TimeUnit.SECONDS);
        scheduler.schedule(new Runnable() {
            public void run() {
                beeperHandle.cancel(true);
            }
        }, 60, TimeUnit.SECONDS);
    }
}
